package me.zhengjie.minbearwcs.listener.outbound;

import lombok.RequiredArgsConstructor;
import me.zhengjie.minbearwcs.dao.outbound.inf.OutboundOrderDao;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.status.OutboundOrderStatus;
import me.zhengjie.observer.event.IWcsEvent;
import me.zhengjie.observer.listener.IWcsEventListener;
import me.zhengjie.observer.type.WcsEventType;
import me.zhengjie.observer.type.inbound.InboundEventType;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


/**
 * 更新工单状态
 */
@Component
@RequiredArgsConstructor
public class OutboundOrderStartListener implements IWcsEventListener {

    private final OutboundOrderDao outboundOrderDao;

    private final Object lock = new Object();

    @Override
    @Transactional
    public void onEvent(IWcsEvent wcsEvent) {
        String outboundOrderCode = (String) wcsEvent.getSource();

        // 更新工单状态
        if (OutboundOrderStatus.INIT == outboundOrderDao.selectStatusByOutboundOrderCode(outboundOrderCode)) {
            synchronized (lock) {
                if (OutboundOrderStatus.INIT == outboundOrderDao.selectStatusByOutboundOrderCode(outboundOrderCode)) {
                    outboundOrderDao.updateStatusByOutboundOrderCode(outboundOrderCode,OutboundOrderStatus.PROCESSING);
                    outboundOrderDao.updateStartTimeByOutboundOrderCode(outboundOrderCode,LocalDateTime.now());
                }
            }
        }
    }

    @Override
    public WcsEventType getEventType() {
        return InboundEventType.OUTBOUND_ORDER_START;
    }
}
